<?php
class KolSys_Chat_Clean
{
	public function parseIncomingChatMessage($text)
	{
		return parseChatMessages($text, true);
	}
    
	public function parseOutgoingChatMessages($text)
	{
		return parseChatMessages($text,false);
	}
	
	public function parseChatMessages($text, $isIncoming)
	{
		$chats=array();
		$r=new KolSys_Chat_RegExp;
		if(!$isIncoming)
		{
			//outgoing Private Message
				if($r->isOutGoingPM($text))
				{
					$chat=$r->getLastResult();
					$text=substr($text,0,$chat['matchOffset'][0]).substr($text,$chat['matchOffset'][1]);
					$chats[]=$chat;
				}
			//user changed chat channels through /c or /s
				if($r->isNewChannelChange($text))
				{
					$chat=$r->getLastResult();
					$text=substr($text,0,$chat['matchOffset'][0]).substr($text,$chat['matchOffset'][1]);
					$chats[]=$chat;
				}
			//list of channels the user is listening to via /l
				if($r->isChatListenResponse($text))
				{
					$chat=$r->getLastResult();
					$text=substr($text,0,$chat['matchOffset'][0]).substr($text,$chat['matchOffset'][1]);
					$chats[]=$chat;
				}
			// user types /l <channel> resulting in now listening to <channel>
				if($r->isChatStartListen($text))
				{
					$chat=$r->getLastResult();
					$text=substr($text,0,$chat['matchOffset'][0]).substr($text,$chat['matchOffset'][1]);
					$chats[]=$chat;
				}
			// user types /l <channel> resulting in no longer listening to <channel>
				if($r->isChatStopListen($text))
				{
					$chat=$r->getLastResult();
					$text=substr($text,0,$chat['matchOffset'][0]).substr($text,$chat['matchOffset'][1]);
					$chats[]=$chat;
				}
		}//if

		$lines = explode('<br>',$text);
		foreach($lines as $line)
		{
			//Strips HTML comments from the text
				$line=KolSys_RegExp::getObj("htmlComment")->replace('',$line);
				$line=trim($line);
				if(strlen($line)==0){continue;}
			//Mod Announcements and Mod Warnings leave leading </font> tags at the beginning of the next message
			//This method will remove them and also skip the line if that is all there is
				if(substr($line,0,7)=='</font>')
				{
					if(strlen($line)==7){continue;}
					$line=trim(substr($line,7));
				}
			//System Announcements leave leading </b></font> tags at the beginning of the next message
			//This method will remove them and also skip the line if that is all there is
				if(substr($line,0,11)=='</b></font>')
				{
					if(strlen($line)==11){continue;}
					$line=trim(substr($line,11));

				}
			//Parsing chat "manually" without the help of a regular expression
			$chat=array();
			$parsedChat=false;

			//See if this message was posted to a different channel.
			KolSys_RegExp::getObj("chatChannel");
		}

		return array('chats'=>$chats,'text'=>$text);
	}//method
}//class